package com.jacky.demo.spec;

import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by jacky on 2018/5/21.
 *
 * 只能hook自己的应用
 */

public class HookHelper {

    public static void attachContext() {
        try {
            Class<?> c = Class.forName("android.app.ActivityManagerNative");

            Field field = c.getDeclaredField("gDefault");

            field.setAccessible(true);

            //返回ActivityManagerNative对象
            Object amn = field.get(null);

            Class<?> k = Class.forName("android.util.Singleton");

            Field field1 = k.getDeclaredField("mInstance");

            field1.setAccessible(true);

            //拿到ActivityManagerProxy对象 代理ActivityManagerNative对象的子类ActivityManagerService
            //为什么不是IActivityManager对象
            //因为在gDefault对象的 实现方法 onCreate()方法中 asInterface(b)返回的是  return new ActivityManagerProxy(obj) 具体可以看源码

            Object iActivityManager = field1.get(amn);

            IamInvocationHandler iamInvocationHandler = new IamInvocationHandler(iActivityManager);

            Object object = Proxy.newProxyInstance(iamInvocationHandler.getClass().getClassLoader(), iActivityManager.getClass().getInterfaces(), iamInvocationHandler);

            field1.set(amn, object);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    static class IamInvocationHandler implements InvocationHandler {

        Object iamObject;

        public IamInvocationHandler(Object iamObject) {
            this.iamObject = iamObject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//            Log.e(TAG, method.getName());
            if ("startActivity".equals(method.getName())) {
                Log.e("tag", "要开始启动了 啦啦啦啦啦啦  ");
            }
            return method.invoke(iamObject, args);
        }
    }
}
